import cfg from './config.mjs'
import Fastify from 'fastify'
import cors from '@fastify/cors'
import mongodb from '@fastify/mongodb'
import live from './routers/live.mjs'
import api from './routers/api.mjs'
import formbody from '@fastify/formbody'

const fastify = Fastify({
  logger: true
})

fastify.register(cors, {
  // put your options here
})

// 支持x-www-form-urlencoded
fastify.register(formbody)
// console.log(cfg.mongodbUrl)
fastify.register(mongodb, {
  // force to close the mongodb connection when app stopped
  // the default value is false
  forceClose: true,
  database: cfg.database,
  url: cfg.mongodbUrl
})

// live返回系统基本信息
fastify.register(live)
fastify.register(api, {
  prefix: '/api'
})

// Run the server!
const start = async () => {
  try {
    await fastify.listen({port:cfg.port, host:'0.0.0.0'})
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()
